const PlayerAni = function (playerImgs, cellSize) {
  const { AnimatedSprite, Container } = PIXI;

  const player = new Container();

  const tw = new TWEEN.Tween(player).easing(TWEEN.Easing.Quadratic.Out);

  const onPlayeMove = (e) => {
    return new Promise((res, rej) => {
      const { name } = player.getChildAt(0);
      console.log(e.key)
      switch (e.key) {
        case "ArrowDown":
          if (name !== "down") {
            player.removeChildAt(0);
            const { down } = player.anis;
            player.addChild(down);
            down.play();
          }

          player.pos.y += 1;

          break;
        case "ArrowLeft":
          if (name !== "left") {
            player.removeChildAt(0);
            const { left } = player.anis;
            player.addChild(left);
            left.play();
          }
          player.pos.x -= 1;
          break;
        case "ArrowRight":
          if (name !== "right") {
            player.removeChildAt(0);
            const { right } = player.anis;
            player.addChild(right);
            right.play();
          }

          player.pos.x += 1;

          break;
        case "ArrowUp":
          if (name !== "up") {
            player.removeChildAt(0);
            const { up } = player.anis;
            player.addChild(up);
            up.play();
          }
          player.pos.y -= 1;

          break;
      }
      tw.to({ x: player.pos.x * cellSize, y: player.pos.y * cellSize }, 200)
        .start()
        .onComplete(() => {
          res();
        });
    });
  };

  const createPalyerAni = (imgs) => {
    const createAni = (imgArr, name) => {
      const ani = new AnimatedSprite(imgArr);
      ani.animationSpeed = 0.1;
      ani.width = cellSize;
      ani.height = cellSize;
      ani.name = name;
      return ani;
    };

    return {
      down: createAni(imgs.slice(0, 4), "down"),
      left: createAni(imgs.slice(4, 8), "left"),
      right: createAni(imgs.slice(8, 12), "right"),
      up: createAni(imgs.slice(12, 16), "up"),
    };
  };

  player.anis = createPalyerAni(playerImgs);

  // 默认动画
  const down = player.anis.down;
  player.addChild(down);
  down.play();

  return {
    player,
    onPlayeMove,
  };
};
